import javax.swing.*;
import javax.swing.Timer;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class LoveMessage {
    private static final List<JFrame> windows = new ArrayList<>();
    private static final String[] MESSAGES = {
            "我想你了！", "你好可爱！", "今天过得怎么样？", "你是我的一切",
            "爱你哦！", "好想你呀", "你是最棒的！", "心心念念都是你",
            "遇见你真好", "你笑起来真好看", "想抱抱你", "永远在一起"
    };
    private static final Color[] COLORS = {
            new Color(255, 182, 193), // 浅粉色
            new Color(255, 105, 180), // 热粉色
            new Color(255, 192, 203), // 粉色
            new Color(219, 112, 147), // 深粉色
            new Color(255, 160, 122), // 浅橙红
            new Color(240, 128, 128)  // 浅珊瑚色
    };
    private static int messageCount = 0;
    private static JLabel counterLabel;
    private static JSpinner windowCountSpinner;
    private static Timer autoTimer;

    public static void main(String[] args) {
        // 创建控制面板
        createControlPanel();

        // 创建初始窗口
        createInitialWindows();
    }

    private static void createControlPanel() {
        JFrame controlFrame = new JFrame("爱心消息控制面板");
        controlFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        controlFrame.setSize(350, 300);
        controlFrame.setLocation(100, 100);
        controlFrame.setLayout(new GridLayout(0, 1, 5, 5));

        // 标题
        JLabel titleLabel = new JLabel("爱心消息生成器", SwingConstants.CENTER);
        titleLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 18));
        titleLabel.setForeground(new Color(255, 105, 180));

        // 计数器标签
        counterLabel = new JLabel("当前窗口数量: 0", SwingConstants.CENTER);
        counterLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 14));

        // 窗口数量设置
        JPanel countPanel = new JPanel(new FlowLayout());
        JLabel countLabel = new JLabel("设置窗口数量:");
        countLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 12));

        SpinnerNumberModel spinnerModel = new SpinnerNumberModel(10, 1, 100, 1);
        windowCountSpinner = new JSpinner(spinnerModel);
        windowCountSpinner.setFont(new Font("Microsoft YaHei", Font.PLAIN, 12));

        countPanel.add(countLabel);
        countPanel.add(windowCountSpinner);

        // 创建按钮面板
        JPanel buttonPanel = new JPanel(new GridLayout(2, 2, 5, 5));

        // 创建按钮
        JButton createButton = new JButton("创建指定数量");
        styleButton(createButton, new Color(255, 182, 193));

        JButton clearButton = new JButton("清除所有窗口");
        styleButton(clearButton, new Color(173, 216, 230));

        JButton autoButton = new JButton("开始自动模式");
        styleButton(autoButton, new Color(144, 238, 144));

        JButton stopAutoButton = new JButton("停止自动模式");
        styleButton(stopAutoButton, new Color(255, 160, 122));

        // 添加按钮事件
        createButton.addActionListener(e -> createMultipleWindows());

        clearButton.addActionListener(e -> clearAllWindows());

        autoButton.addActionListener(e -> startAutoMode());

        stopAutoButton.addActionListener(e -> stopAutoMode());

        // 添加到按钮面板
        buttonPanel.add(createButton);
        buttonPanel.add(clearButton);
        buttonPanel.add(autoButton);
        buttonPanel.add(stopAutoButton);

        // 添加组件到控制面板
        controlFrame.add(titleLabel);
        controlFrame.add(counterLabel);
        controlFrame.add(countPanel);
        controlFrame.add(buttonPanel);

        // 添加说明文本
        JTextArea infoArea = new JTextArea();
        infoArea.setText("使用说明:\n" +
                "• 设置窗口数量后点击'创建指定数量'\n" +
                "• 自动模式会持续创建窗口直到达到设置数量\n" +
                "• 点击任意消息窗口可关闭它");
        infoArea.setFont(new Font("Microsoft YaHei", Font.PLAIN, 11));
        infoArea.setBackground(controlFrame.getBackground());
        infoArea.setEditable(false);
        controlFrame.add(infoArea);

        controlFrame.setVisible(true);
    }

    private static void styleButton(JButton button, Color color) {
        button.setFont(new Font("Microsoft YaHei", Font.PLAIN, 12));
        button.setBackground(color);
        button.setFocusPainted(false);
        button.setBorder(BorderFactory.createRaisedBevelBorder());

        // 添加鼠标悬停效果
        button.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseEntered(MouseEvent e) {
                button.setBackground(color.brighter());
            }

            @Override
            public void mouseExited(MouseEvent e) {
                button.setBackground(color);
            }
        });
    }

    private static void createInitialWindows() {
        // 创建3个初始窗口
        for (int i = 0; i < 3; i++) {
            createSingleWindow();
            try {
                Thread.sleep(300); // 延迟创建，形成动画效果
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private static void createMultipleWindows() {
        int targetCount = (Integer) windowCountSpinner.getValue();
        int windowsToCreate = targetCount - messageCount;

        if (windowsToCreate <= 0) {
            JOptionPane.showMessageDialog(null,
                    "当前窗口数量已超过或等于目标数量!",
                    "提示",
                    JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        // 在新线程中创建窗口，避免阻塞UI
        new Thread(() -> {
            for (int i = 0; i < windowsToCreate; i++) {
                createSingleWindow();
                try {
                    Thread.sleep(100); // 创建间隔
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private static void createSingleWindow() {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = createMessageWindow();
            windows.add(frame);
            messageCount++;
            updateCounter();

            // 添加关闭动画
            addCloseAnimation(frame);
        });
    }

    private static JFrame createMessageWindow() {
        JFrame frame = new JFrame("❤️");
        frame.setUndecorated(true); // 无边框
        frame.setBackground(new Color(0, 0, 0, 0)); // 透明背景

        // 获取屏幕尺寸
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        Random random = new Random();
        int x = random.nextInt(screenSize.width - 250);
        int y = random.nextInt(screenSize.height - 100);

        // 设置窗口位置和大小
        frame.setLocation(x, y);
        frame.setSize(250, 80);

        // 创建自定义面板（圆角边框）
        JPanel panel = new RoundedPanel(20);
        panel.setLayout(new BorderLayout());

        // 随机选择消息和颜色
        String message = MESSAGES[random.nextInt(MESSAGES.length)];
        Color bgColor = COLORS[random.nextInt(COLORS.length)];
        panel.setBackground(bgColor);

        // 创建标签
        JLabel label = new JLabel(message, SwingConstants.CENTER);
        label.setFont(new Font("Microsoft YaHei", Font.BOLD, 16));
        label.setForeground(Color.DARK_GRAY);

        // 添加鼠标悬停效果
        label.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseEntered(MouseEvent e) {
                panel.setBackground(bgColor.darker());
                label.setCursor(new Cursor(Cursor.HAND_CURSOR));
            }

            @Override
            public void mouseExited(MouseEvent e) {
                panel.setBackground(bgColor);
                label.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
            }

            @Override
            public void mouseClicked(MouseEvent e) {
                // 点击时关闭窗口
                closeWindowWithAnimation(frame);
            }
        });

        panel.add(label, BorderLayout.CENTER);
        frame.add(panel);
        frame.setVisible(true);

        // 添加出现动画
        addAppearAnimation(frame);

        return frame;
    }

    private static void addAppearAnimation(JFrame frame) {
        frame.setOpacity(0f);
        Timer timer = new Timer(10, new ActionListener() {
            float opacity = 0f;
            @Override
            public void actionPerformed(ActionEvent e) {
                opacity += 0.05f;
                frame.setOpacity(Math.min(opacity, 1f));
                if (opacity >= 1f) {
                    ((Timer)e.getSource()).stop();
                }
            }
        });
        timer.start();
    }

    private static void addCloseAnimation(JFrame frame) {
        frame.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                closeWindowWithAnimation(frame);
            }
        });
    }

    private static void closeWindowWithAnimation(JFrame frame) {
        Timer timer = new Timer(10, new ActionListener() {
            float opacity = 1f;
            @Override
            public void actionPerformed(ActionEvent e) {
                opacity -= 0.05f;
                frame.setOpacity(Math.max(opacity, 0f));
                if (opacity <= 0f) {
                    ((Timer)e.getSource()).stop();
                    frame.dispose();
                    windows.remove(frame);
                    messageCount--;
                    updateCounter();
                }
            }
        });
        timer.start();
    }

    private static void startAutoMode() {
        if (autoTimer != null && autoTimer.isRunning()) {
            JOptionPane.showMessageDialog(null, "自动模式已在运行!", "提示", JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        int maxWindows = (Integer) windowCountSpinner.getValue();

        autoTimer = new Timer(800, e -> {
            if (messageCount < maxWindows) {
                createSingleWindow();
            } else {
                stopAutoMode();
                JOptionPane.showMessageDialog(null,
                        "已达到目标窗口数量(" + maxWindows + ")，自动模式已停止",
                        "提示",
                        JOptionPane.INFORMATION_MESSAGE);
            }
        });
        autoTimer.start();

        JOptionPane.showMessageDialog(null,
                "自动模式已启动，将创建窗口直到达到" + maxWindows + "个",
                "提示",
                JOptionPane.INFORMATION_MESSAGE);
    }

    private static void stopAutoMode() {
        if (autoTimer != null && autoTimer.isRunning()) {
            autoTimer.stop();
            JOptionPane.showMessageDialog(null, "自动模式已停止", "提示", JOptionPane.INFORMATION_MESSAGE);
        }
    }

    private static void clearAllWindows() {
        // 为每个窗口添加关闭动画
        for (JFrame frame : new ArrayList<>(windows)) {
            closeWindowWithAnimation(frame);
        }

        // 重置计数器
        messageCount = 0;
        updateCounter();
    }

    private static void updateCounter() {
        counterLabel.setText("当前窗口数量: " + messageCount);
    }

    // 自定义圆角面板
    static class RoundedPanel extends JPanel {
        private int cornerRadius;

        public RoundedPanel(int radius) {
            super();
            cornerRadius = radius;
            setOpaque(false);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Dimension arcs = new Dimension(cornerRadius, cornerRadius);
            int width = getWidth();
            int height = getHeight();
            Graphics2D graphics = (Graphics2D) g;
            graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

            // 绘制圆角矩形背景
            graphics.setColor(getBackground());
            graphics.fillRoundRect(0, 0, width-1, height-1, arcs.width, arcs.height);

            // 绘制边框
            graphics.setColor(getBackground().darker());
            graphics.drawRoundRect(0, 0, width-1, height-1, arcs.width, arcs.height);
        }
    }
}